package com.ruoyi.common.utils.flask;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.http.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpFlask {
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @return 所代表远程资源的响应结果
     */
    public static String sendGetFlask(String url) {
        log.info("sendGetFlask - {}", url);
        return HttpUtils.sendGet(url);
    }

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendGetFlask(String url, String param) {
        log.info("sendGetFlask - {}", url);
        return HttpUtils.sendGet(url, param, Constants.UTF8);
    }

    public static String sendPostFlask(String url, String param) {
        log.info("sendPostFlask - {}", url);
        return HttpUtils.sendPost(url, param);
    }

    // java 对象转 map
    private static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        if (obj == null) return null;
        Map<String, Object> map = new HashMap<>();
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }

    public static String getKeyAndValueString(Object object) throws IllegalAccessException {
        Map<String, Object> map = objectToMap(object);
        String result = "";
        try {
            List<Map.Entry<String, Object>> infoIds = new ArrayList(map.entrySet());
            StringBuilder stringBuilder = new StringBuilder();
            for (Map.Entry<String, Object> item : infoIds) {
                String key = item.getKey();
                if (!"serialVersionUID".equals(key)) {
                    String val = (String) item.getValue();
                    stringBuilder.append(key).append("=").append(val).append("&");
                }
            }
            result = stringBuilder.toString().substring(0, stringBuilder.length() - 1);
        } catch (Exception e) {
            e.printStackTrace(System.out);
            return null;
        }
        return result;
    }

}
